const express = require('express');
const cors = require('cors');
const path = require('path');

// 导入路由模块
const authRoutes = require('./routes/auth');
const addressRoutes = require('./routes/address');
const messageRoutes = require('./routes/message');
const cartRoutes = require('./routes/cart');
const appraiseRoutes = require('./routes/appraise');
const detailRoutes = require('./routes/detail');

const app = express();

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../public')));

// 错误处理中间件
app.use((err, req, res, next) => {
    if (err instanceof SyntaxError && err.status === 400 && 'body' in err) {
        return res.status(400).json({
            success: "失败",
            msg: "请求数据格式错误，请确保发送正确的JSON格式",
            error: err.message
        });
    }
    next();
});

// 路由配置
app.use('/auth', authRoutes);
app.use('/address', addressRoutes);
app.use('/message',messageRoutes);
app.use('/cart',cartRoutes);
app.use('/appraise',appraiseRoutes);
app.use('/detail',detailRoutes)
// 全局错误处理
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        success: "失败",
        msg: "服务器内部错误",
        error: err.message
    });
});

// 启动服务器
const PORT = process.env.PORT || 3005;
app.listen(PORT, () => {
    console.log(`服务器已启动，监听端口 ${PORT}`);
});

module.exports = app;